package com.bjsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjsxt.commons.pojo.BaizhanResult;
import com.bjsxt.mapper.TbUserMapper;
import com.bjsxt.pojo.TbUser;
import com.bjsxt.service.PassportService;
import com.bjsxt.utils.IDUtils;
import com.google.errorprone.annotations.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

/**
 * @author coder_z
 * @date 2023/3/20
 **/
@Service
public class PassportServiceImpl implements PassportService {
    @Autowired
    private TbUserMapper tbUserMapper;
    @Override
    public BaizhanResult check(String value, Integer flag) {
        QueryWrapper Wrapper = new QueryWrapper();
        if(flag==1){
            Wrapper.eq("username",value);
        }else if(flag==2){
            Wrapper.eq("phone",value);
        }else if(flag==3){
            Wrapper.eq("email",value);
        }
        TbUser tbUser = tbUserMapper.selectOne(Wrapper);
        if(tbUser==null){
            return BaizhanResult.ok();
        }
        return BaizhanResult.error("服务器消息，信 息已被注册");
    }

    @Override
    public BaizhanResult register(TbUser user) {

        user.setId(IDUtils.genItemId());
        Date date = new Date();
        user.setCreated(date);
        user.setUpdated(date);
//        密码进行加密 在企业开发中 一定会给一个工具类直接调用工具类即可
//        直接使用spring framwork工具类 使用md5加密(基于hash算法实现)
        String pwdMD5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pwdMD5);
        int index = tbUserMapper.insert(user);
        if(index==1){
            return BaizhanResult.ok();
        }
        return BaizhanResult.error("服务器消息-用户注册失败");
    }

    @Override
    public BaizhanResult login(TbUser user) {
//        由于是明文密码 所以要进行加密转换
        String pwdMD5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pwdMD5);
//        参数中可能是username,phone,email
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.or().eq("username",user.getUsername()).eq("password",user.getPassword())
               .or().eq("phone",user.getUsername()).eq("password",user.getPassword())
                .or().eq("email",user.getUsername()).eq("password",user.getPassword());
        TbUser tbUser = tbUserMapper.selectOne(wrapper);
        if(tbUser!=null){
            tbUser.setPassword("");
            return BaizhanResult.ok(tbUser);
        }
        return BaizhanResult.error("服务器消息-登录失败");
    }
}
